package org.grow.secure.service;

import org.grow.secure.entity.UserInfo;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @Author: xwg
 * @CreateDate: 21-7-20
 */

@Service
public class NormalAccessDecision implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection)
            throws AccessDeniedException, InsufficientAuthenticationException {
//        进行第三部 取交集

        Collection<? extends GrantedAuthority> rolesFromUsername = authentication.getAuthorities();
        Collection<ConfigAttribute> rolesFromUrl = collection;
        FilterInvocation fi = (FilterInvocation) o;
        String requestUrl = fi.getRequestUrl();
        System.out.println("AccessDecision: 用户访问的url "+requestUrl);
        System.out.println("AccessDecision: rolesFromUsername "+rolesFromUsername);
        System.out.println("AccessDecision: rolesFromUrl "+rolesFromUrl);

        Boolean a = false;
        for (GrantedAuthority grantedAuthority : rolesFromUsername) {
            String authority = grantedAuthority.getAuthority();
            for (ConfigAttribute configAttribute : rolesFromUrl) {
                String attribute = configAttribute.getAttribute();

                    if (authority.equals(attribute)){
                        a=true;
                        break;
                    }

            }
        }
//        if (a){
//            System.out.println("用户有权限访问该url");
//        }
        if (!a){
            System.out.println("无交集，用户无权限访问该url");
            throw new AccessDeniedException("无交集，用户"+authentication.getName()+"无权限访问"+requestUrl);
        }


    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
